package src;

import java.util.ArrayList;

public class StringCalculator {
	
  public static int add(String data) {
	  
	  		int tulemus = 0;
	  		String delimiter = ",";
	  		
	  		if  (data.contains("//")) {
	  			if (data.contains("[")) {
	  				int lastMark = data.indexOf("]");
	  				int howMany = lastMark-3;
	  				delimiter = "";
	  				for (int i = 0; i<howMany;i++) {
	  					delimiter += "#";
	  				}
	  				data = data.replaceAll("\\*\\*\\*", delimiter);
	  				data = data.substring(lastMark+2);
	  			} else {
	  				delimiter=data.substring(2, 3);
		  			data=data.substring(4);
	  			}
	  		}
	  		
			if (data.contains(delimiter) || data.contains("\n")) {
				
				String[] pooled = (data.replace("\n", delimiter)).split(delimiter);
		  		ArrayList<String> lessThanZero = new ArrayList<String>();
				if (delimiter.equals(".")){
					pooled = (data.replace("\n", delimiter)).split("\\.");
				}	
				for(int i = 0; i<pooled.length;i++) {
					
					if (Integer.parseInt(pooled[i]) <= 1000 && Integer.parseInt(pooled[i]) > 0) {
						tulemus += Integer.parseInt(pooled[i]);
					} else if (Integer.parseInt(pooled[i]) < 0) {
						lessThanZero.add(pooled[i]);
					}
				}
				if (!lessThanZero.isEmpty()) {
					String stringOfIllegalArguments = "";
					for (String s : lessThanZero) {
						stringOfIllegalArguments += " " + s + ",";
					}
					throw new IllegalArgumentException("Negative values not allowed:" + stringOfIllegalArguments.substring(0, stringOfIllegalArguments.length()-1));
				}
			}	else if (!data.equals("")) {
					tulemus += Integer.parseInt(data);
			}
			return tulemus;		
  }
}
